//
//  LBXFileDownServer.m
//  WebServerTools
//
//  Created by 夏利兵 on 2020/9/24.
//  Copyright © 2020 com.lbx. All rights reserved.
//

#import "LBXFileDownServer.h"
#import "GCDWebServer.h"
#import <ifaddrs.h>
#import <arpa/inet.h>

@interface LBXFileDownServer()
@property (nonatomic, strong) GCDWebServer* fileDownServer;

@end

@implementation LBXFileDownServer

+ (instancetype)sharedManager
{
    static LBXFileDownServer* _sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[LBXFileDownServer alloc] init];
        _sharedInstance.port = 60001;
        
    });
    
    return _sharedInstance;
}

- (BOOL)start
{
    
    if (_fileDownServer) {
        return YES;
    }
        //理论1024 之下的没有权限
    NSUInteger port = self.port;
       
        
    GCDWebServer* webServer = [[GCDWebServer alloc] init];
    self.fileDownServer = webServer;
    [webServer addGETHandlerForBasePath:@"/" directoryPath:self.fileDir indexFilename:nil cacheAge:3600 allowRangeRequests:YES];
        //    Failed binding IPv4 listening socket: Operation not permitted (1)
        
        //卡住主线程
    //    [webServer runWithPort:port bonjourName:@"test"];
        
       //异步
       if( ![webServer startWithPort:port bonjourName:@"test"] )
       {
//           self.showIpLabel.stringValue = [NSString stringWithFormat:@"启动失败 端口号：%lu (注意是不是端口被占用了)",(unsigned long)port];
//            self.webStaticServer = nil;
           self.errMsg = [NSString stringWithFormat:@"启动失败 端口号：%lu (注意是不是端口被占用了)",(unsigned long)port];
           
           self.fileDownServer = nil;
           return NO;
       }
    
    self.published = YES;
       
    return YES;
}


- (void)stop
{
    if (_fileDownServer) {
        [_fileDownServer stop];
        self.fileDownServer = nil;
        self.published = NO;
    }
}



- (NSString*)visitUrl
{
    NSString *visitUrl = [NSString stringWithFormat:@"http://%@:%lu/",[self deviceIPAdress],(unsigned long)self.port];
    
    return visitUrl;
}

- (NSString *)deviceIPAdress {
    
    NSString *address = @"";
    
    struct ifaddrs *interfaces = NULL;
    
    struct ifaddrs *temp_addr = NULL;
    
    int success = 0;
    
    success = getifaddrs(&interfaces);
    
    if (success == 0) { // 0 表示获取成功
        
        temp_addr = interfaces;
        
        while (temp_addr != NULL) {
            
            if( temp_addr->ifa_addr->sa_family == AF_INET) {
                
                // Check if interface is en0 which is the wifi connection on the iPhone
                //                NSLog(@"%@",[NSString stringWithUTF8String:temp_addr->ifa_name]);
                //                 NSString* str = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                //                NSLog(@"%@",str);
                
                if ([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"] || [[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en1"] ) {
                    
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                    
                }
            }
            
            temp_addr = temp_addr->ifa_next;
        }
    }
    
    freeifaddrs(interfaces);
    
    return address;
    
}

@end
